package com.ruan.controller;

import com.ruan.common.Code;
import com.ruan.common.Result;
import com.ruan.mapper.CommonUserMapper;
import com.ruan.pojo.CommonUser;
import com.ruan.service.CommonUserService;
import com.ruan.utils.SMSUtils;
import com.ruan.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
@CrossOrigin
@Slf4j

public class SMSController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CommonUserService commonUserService;

    @GetMapping("/getCode")
    public Result getCode(String phone){
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        log.info("生成的验证码是：{}",code);
        log.info("手机号是：{}",phone);

        CommonUser commonUser = commonUserService.selectOneByPhone(phone);//后台报错是正常的

        if (commonUser != null && "正常".equals(commonUser.getStatus())) {
            return new Result(Code.REGISTER_ERR, "该手机号已注册！");
        }
        else {//commonUser为null或者状态不为"正常"

        }

        //调用腾讯云提供的短信服务API完成发送短信
        Result result = SMSUtils.sendCode(phone, code);

        //将生成的验证码缓存到redis中，phone为key，code为value
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(phone,code,5, TimeUnit.MINUTES);

        return result;
    }
}
